"""
@File    : mysql_operate.py
@Time    : 2021/11/15 22:12
@Author  : chenhuayan
@Software: PyCharm
"""
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import pymysql
from config.sql_connections import MYSQL_CONN
# from faker import Faker


class MysqlDb(object):
    def __init__(self, db_name, res_format='tuple'):
        # 建立数据库连接
        self.conn = pymysql.connect(**MYSQL_CONN[db_name])
        # 通过cursor() 创建游标对象，并让查询结果以字典格式输出
        if res_format == 'dict':
            self.cour = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
        else:
            self.cour = self.conn.cursor()
        print(f'{db_name}数据库连接成功~')

    def select_db(self, sql):
        """查询"""
        # 检查连接是否端口，如果断开则进行重连
        self.conn.ping(reconnect=True)
        # 执行sql
        self.cour.execute(sql)
        # 获取查询结果
        res = self.cour.fetchall()
        return res

    def excute_db(self, sql):
        """更新/新增/删除"""
        try:
            # 执行sql
            num = self.cour.execute(sql)
            self.conn.commit()
            return num
        except Exception as e:
            print(f'操作出现错误：{e}')


# def getValue():
#     fake = Faker('en_US')
#     return fake.name()
